import {PlusOutlined, UploadOutlined} from '@ant-design/icons';
import {Button, message, Drawer, FormInstance, Popconfirm, Image, Upload} from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  ModalForm,
  ProFormText,
  ProFormSelect,
  ProFormUploadButton,
  ProFormDatePicker,
} from '@ant-design/pro-form';
import ProDescriptions, { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import { removeData, dataList, addData, updateData, loadData } from './service';
import type { VehicleBody, VehicleListItem, VehicleListPagination } from './data';
import { UploadFile } from 'antd/lib/upload/interface';
import { loadEmployeeSelect } from '@/pages/Employee/List/service';

/**
 * 添加节点
 *
 * @param fields
 * @param mode
 */

const handleAdd = async (fields: VehicleBody, mode: boolean) => {
  const hide = message.loading(mode ? '正在保存' : '正在添加');

  try {
    mode ? await updateData({ ...fields }) : await addData({ ...fields });
    hide();
    message.success(mode ? '保存成功' : '添加成功');
    return true;
  } catch (error) {
    // hide();
    // message.error(mode ? '保存失败请重试' : '添加失败请重试');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows: VehicleListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeData(selectedRows.map((row) => row.vehicleId));
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const requestEmployee = async (param: any) => {
  return loadEmployeeSelect(param).then(({ data }) => {
    return data;
  });
};
const VehiclePage: React.FC = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();
  const [currentRow, setCurrentRow] = useState<VehicleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<VehicleListItem[]>([]);

  const columns: ProColumns<VehicleListItem>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'indexBorder',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
                (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '车牌号',
      dataIndex: 'vehicleNo',
    },
    {
      title: '车辆类型',
      dataIndex: 'vehicleType',
      valueEnum: {
        1: {
          text: '道路货运车辆',
        },
        2: {
          text: '道路客运车辆',
        },
        3: {
          text: '非营运客车',
        },
        4: {
          text: '非营运货车',
        },
        5: {
          text: '4.5吨以下货车',
        },
        6: {
          text: '其他',
        },
      },
    },

    {
      title: '载客',
      search: false,
      dataIndex: 'carryingCapacity',
    },
    {
      search: false,
      title: '行驶证',
      dataIndex: 'vehicleLicence',
      render: (_, record) =>
        record.vehicleLicence ? (
          <a target={'_blank'} href={record.vehicleLicence}>
            查看行驶证
          </a>
        ) : (
          <>-</>
        ),
    },
    {
      title: '行驶证编号',
      search: false,
      dataIndex: 'vehicleLicenceNo',
    },
    {
      search: false,
      title: '行驶证注册时间',
      dataIndex: 'vehicleLicenceStartTime',
    },

    {
      search: false,
      title: '营运证',
      dataIndex: 'operationCertificate',
      render: (_, record) =>
        record.operationCertificate ? (
          <a target={'_blank'} href={record.operationCertificate}>
            查看营运证
          </a>
        ) : (
          <>-</>
        ),
    },
    {
      title: '营运证编号',
      search: false,
      dataIndex: 'operationCertificateNo',
    },
    {
      title: '营运证生效时间',
      dataIndex: 'operationCertificateStartTime',
      search: false,
    },
    {
      title: '负责人',
      dataIndex: 'employeeId',
      valueType: 'select',
      request: async () => {
        let result = await loadEmployeeSelect({});
        return result.data;
      },
    },
    {
      title: '负责人电话',
      search: false,
      dataIndex: 'phone',
    },
    // {
    //   title: '创建时间',
    //   sorter: true,
    //   dataIndex: 'createTime',
    //   valueType: 'dateTime',
    //   search: false,
    // },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInDescriptions: true,
      render: (_, record) => [
        <a
          key="view"
          onClick={() => {
            formRef.current?.resetFields();
            setCurrentRow(record);
            setShowDetail(true);
          }}
        >
          查看
        </a>,
        <a
          key="edit"
          onClick={() => {
            formRef.current?.resetFields();
            console.log(record);
            setCurrentRow(record);
            setEditMode(true);
            handleModalVisible(true);
          }}
        >
          编辑
        </a>,

        <Popconfirm
          key="delete"
          okButtonProps={{ danger: true }}
          title={`确认删除车辆：${record.vehicleNo}?`}
          onConfirm={async () => {
            setCurrentRow(record);
            await handleRemove([record]);
            actionRef.current?.reloadAndRest?.();
          }}
          okText="删除"
          cancelText="取消"
        >
          <a href="#"> 删除 </a>
        </Popconfirm>,
      ],
    },
  ];

  const [editMode, setEditMode] = useState<boolean>(false);
  const [previewData, setPreviewData] = useState({
    visible: false,
    image: '',
    title: '',
  });

  const uploadProps = {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
    },
    accept: '.pdf',
    multiple: false,
    // @ts-ignore
    onChange({ file }) {
      if (file.status === 'done' && file.response.code !== 200) {
        file.status = 'error';
      }
    },
    onPreview: async (file: UploadFile) => {
      window.open(file?.response?.data?.url || file.url, '_blank');
    },
    name: 'file',
    max: 1,
  };
  const submitCheckFile = (values: VehicleBody, fileName: string, dataName: string) => {
    if (values[fileName]) {
      let file = values[fileName][0];
      values[dataName] = file?.response?.data?.url || file.url;
    }
  };
  const [uploading, setUploading] = useState(false);
  const uploadProps1 = {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`,
      TenantCode: 'e513f45c099239505054fead0a445fa2'
    },
    multiple: false,
    // onPreview: async (file: UploadFile) => {
    //   window.open(file?.response?.data?.path || file.url, '_blank')
    // },
    name: 'file',
    max: 1,
  };
  // @ts-ignore
  return (
    <PageContainer waterMarkProps={{ content: '' }}>
      <ProTable<VehicleListItem, VehicleListPagination>
        headerTitle="车辆列表"
        actionRef={actionRef}
        rowKey="vehicleId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="link"
            key="template"
            onClick={async () => {
              location.href = "https://cdn.51zasafe.com/zun/template/%E8%BD%A6%E8%BE%86%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
            }}
          >
            下载模板
          </Button>,
          <Upload
            key="upload"
            {...uploadProps1}
            accept={'.xls,.xlsx'}
            action={'/v2/enterprise/vehicle/import'}
            showUploadList={false}
            onChange={async (data) => {
              let file = data.file;
              if (file.status === 'uploading') {
                setUploading(true);
              } else {
                setUploading(false);
              }
              if (file.status === 'done' && file.response.code !== 200) {
                message.error(file.response.msg);
                file.status = 'error';
              } else if (file.status === 'done' && file.response.code === 200) {
                message.success('上传成功');
                // @ts-ignore
                actionRef?.current?.reloadAndRest();
              }
            }}
          >
            <Button type="primary" loading={uploading} icon={<UploadOutlined/>}>
              导入
            </Button>
          </Upload>,
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setEditMode(false);
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={dataList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              个车辆
            </div>
          }
        >
          <Popconfirm
            key="delete"
            title={`确认删除选中的${selectedRowsState.length}个车辆?`}
            okButtonProps={{ danger: true }}
            onConfirm={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            okText="删除"
            cancelText="取消"
          >
            <Button danger>批量删除</Button>
          </Popconfirm>
          {/*<Button type="primary">批量审批</Button>*/}
        </FooterToolbar>
      )}
      <ModalForm<VehicleBody>
        title={currentRow?.vehicleId || 0 > 0 ? '编辑车辆' : '新建车辆'}
        formRef={formRef}
        visible={createModalVisible}
        onVisibleChange={(visible) => {
          if (!visible) {
            setCurrentRow(undefined);
          }
          handleModalVisible(visible);
        }}
        modalProps={{destroyOnClose: true, maskClosable: false}}
        onFinish={async (value) => {
          console.log(value);

          submitCheckFile(value, 'vehicleLicenceFile', 'vehicleLicence');
          submitCheckFile(value, 'operationCertificateFile', 'operationCertificate');
          submitCheckFile(value, 'vehicleInfoFile', 'vehicleInfo');
          submitCheckFile(value, 'maintainInfoFile', 'maintainInfo');
          console.log(value);

          const success = await handleAdd(value, editMode);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current?.reload();
            }
          }
        }}
        // @ts-ignore
        request={(params: VehicleBody) => {
          console.log(params);
          if (params.vehicleId > 0) {
            return loadData(params).then(({ data }) => {
              if (data.vehicleLicence)
                data.vehicleLicenceFile = [
                  {
                    url: data.vehicleLicence,
                    name: '证书图片',
                    status: 'done',
                  },
                ];
              if (data.operationCertificate)
                data.operationCertificateFile = [
                  {
                    url: data.operationCertificate,
                    name: '证书图片',
                    status: 'done',
                  },
                ];
              if (data.vehicleInfo)
                data.vehicleInfoFile = [
                  {
                    url: data.vehicleInfo,
                    name: '证书图片',
                    status: 'done',
                  },
                ];
              if (data.maintainInfo)
                data.maintainInfoFile = [
                  {
                    url: data.maintainInfo,
                    name: '证书图片',
                    status: 'done',
                  },
                ];
              return data;
            });
          } else {
            return new Promise<VehicleBody>((resolve) => {
              resolve({
                vehicleId: 0,
              });
            });
          }
        }}
        params={{ ...currentRow }}
      >
        <ProFormText hidden name="vehicleId" />
        <ProFormText hidden name="employeeName" />
        <ProFormText required label={'车辆名称'} name="vehicleNo" />
        <ProFormSelect
          name="vehicleType"
          required
          label="车辆类型"
          options={[
            {
              label: '道路货运车辆',
              value: 1,
            },
            {
              label: '道路客运车辆',
              value: 2,
            },
            {
              label: '非营运客车',
              value: 3,
            },
            {
              label: '非营运货车',
              value: 4,
            },
            {
              label: '4.5吨以下货车',
              value: 5,
            },
            {
              label: '其他',
              value: 6,
            },
          ]}
        />
        <ProFormText label={'载客(坐)/吨位(吨)'} name="carryingCapacity" />

        <ProFormSelect
          name="employeeId"
          label={'负责人'}
          request={requestEmployee}
          fieldProps={{
            placeholder: '请选择负责人',
            showSearch: true,
            dropdownMatchSelectWidth: false,
            onChange: (a, b) => {
              formRef.current?.setFieldsValue({ phone: b['addition'] });
              formRef.current?.setFieldsValue({ employeeName: b['name'] });
            },
          }}
        />

        <ProFormText label={'负责人电话'} name="phone" />

        <ProFormUploadButton
          name="vehicleLicenceFile"
          label="行驶证（附件）"
          max={1}
          // @ts-ignore
          fieldProps={{ ...uploadProps }}
          action="/v2/enterprise/upload/vehicle"
        />
        <ProFormText label={'行驶证编号'} name="vehicleLicenceNo" />
        <ProFormDatePicker required name="vehicleLicenceStartTime" label="行驶证注册日期" />

        <ProFormUploadButton
          name="operationCertificateFile"
          label="营运证（附件）"
          max={1}
          // @ts-ignore
          fieldProps={{ ...uploadProps }}
          action="/v2/enterprise/upload/vehicle"
        />
        <ProFormText label={'营运证编号'} name="operationCertificateNo" />
        <ProFormDatePicker name="operationCertificateStartTime" label="营运证有效时间" />
        <ProFormDatePicker name="firstCertificateTime" label="首次获得证书时间" />
        <ProFormDatePicker name="lastMaintainTime" label="上次维护日期" />
        <ProFormDatePicker name="nextMaintainTime" label="下次维护日期" />

        <ProFormUploadButton
          name="vehicleInfoFile"
          label="车辆信息"
          max={1}
          // @ts-ignore
          fieldProps={{ ...uploadProps }}
          action="/v2/enterprise/upload/vehicle"
        />
        <ProFormUploadButton
          name="maintainInfoFile"
          label="维护信息"
          max={1}
          // @ts-ignore
          fieldProps={{ ...uploadProps }}
          action="/v2/enterprise/upload/vehicle"
        />
        <ProFormText label={'设备型号'} name="machineType" />
        <ProFormText label={'办证机构'} name="certificateOrg" />
        <ProFormText label={'技术等级'} name="skillLevel" />
        <ProFormText label={'备注'} name="remark" />
      </ModalForm>

      <Image
        width={200}
        style={{ display: 'none' }}
        src={previewData.image}
        preview={{
          visible: previewData.visible,
          src: previewData.image,
          onVisibleChange: (value) => {
            setPreviewData({ image: previewData.image, title: '', visible: value });
          },
        }}
      />
      <Drawer
        width={800}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.vehicleId && (
          <ProDescriptions<VehicleBody>
            column={1}
            bordered={true}
            title={'车辆详情'}
            // @ts-ignore
            request={loadData}
            // layout={'vertical'}
            params={currentRow}
            columns={columns as ProDescriptionsItemProps<VehicleBody>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default VehiclePage;
